/**
 * 
 */
package hu.gbalage.directories.jdo;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;

import hu.gbalage.directories.IDirectory;
import hu.gbalage.directories.IEntry;
import hu.gbalage.owl.cms.disec.PMF;

/**
 * @author balage
 *
 */
public class JDODirectory implements IEntryProvider, IDirectory {

	private static final long serialVersionUID = 173243938209494473L;

	private final Long id;
	
	/**
	 * Opens a directory, which is already exists
	 */
	public JDODirectory(Long id) {
		this.id = id;
	}

	/**
	 * Creates a new Directory
	 * @param parentid
	 * @param name
	 */
	public JDODirectory(Long parentid, String name){
		PersistenceManager pm = PMF.getManager();
		
		JDOEntryData ed = new JDOEntryData();
		ed.entry = this;
		ed.name = name;
		ed.parent = parentid;
		pm.makePersistent(ed);
		
		pm.close();
		id = ed.id;
	}
	
	/* (non-Javadoc)
	 * @see hu.gbalage.directories.jdo.IEntryProvider#getEntry()
	 */
	@Override
	public IEntry getEntry() {
		return this;
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IDirectory#getChildren()
	 */
	@Override
	public List<IEntry> getChildren() {
		List<IEntry> es = new ArrayList<IEntry>();
		for(JDOEntryData ed : JDORootDir.listChildren(id)){
			es.add(ed.entry.getEntry());
		}
		return es;
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IDirectory#put(hu.gbalage.directories.IEntry)
	 */
	@Override
	public boolean put(IEntry entry) {
		return JDORootDir.addChild(EntryCache.get(id), entry);
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IEntry#getName()
	 */
	@Override
	public String getName() {
		return EntryCache.get(id).name;
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IEntry#getParent()
	 */
	@Override
	public IDirectory getParent() {
		return new JDODirectory(EntryCache.get(id).parent);
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IEntry#isDirectory()
	 */
	@Override
	public boolean isDirectory() {
		return true;
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.directories.IEntry#isFile()
	 */
	@Override
	public boolean isFile() {
		return false;
	}

}
